<script>
import {
  BellFilled,
  Collection,
  FolderAdd,
  OfficeBuilding,
  Opportunity,
  Plus,
  SwitchButton,
  UserFilled,
} from "@element-plus/icons-vue";
import MyFooter from "../../components/MyFooter.vue";
import store from "../../store/index.js";
import SettingProjectDialog from "../../components/dialog/SettingProjectDialog.vue";
import AddProjectDialog from "../../components/dialog/AddProjectDialog.vue";
import request, { baseUrlForWebSocket } from "../../utils/Request.js";
import ReadMessageDialog from "../../components/dialog/ReadMessageDialog.vue";
import AddMockDialog from "../../components/dialog/AddMockDialog.vue";
import SharedWorkerUrl from "../../worker/SharedWorker.js?url";

export default {
  components: {
    AddMockDialog,
    ReadMessageDialog,
    AddProjectDialog,
    SettingProjectDialog,
    Plus,
    MyFooter,
    SwitchButton,
    UserFilled,
    OfficeBuilding,
    Collection,
    FolderAdd,
    BellFilled,
    Opportunity,
  },
  computed: {
    store() {
      return store;
    },
    UserFilled() {
      return UserFilled;
    },
    hasMsg() {
      let read = store.state.msgCount > 0;
      if (!read)
        for (let msg of store.state.notifyMessages) {
          if (!msg.isRead) {
            read = true;
            break;
          }
        }

      if (!read)
        for (let msg of store.state.privateMessages) {
          if (!msg.isRead) {
            read = true;
            break;
          }
        }

      if (!read)
        for (let msg of store.state.inviteMessages) {
          if (!msg.isRead) {
            read = true;
            break;
          }
        }
      return read;
    },
  },
  data() {
    return {
      hasAvatar: this.$store.state.isLogin,
      uuid: null,
      sharedWorker: null,
    };
  },
  methods: {
    createWebSocket() {
      // 检查浏览器是否支持SharedWorker
      if (window.SharedWorker && window.WebSocket) {
        console.log(SharedWorkerUrl);
        if (store.state.sharedWorker != null) {
          this.sharedWorker = store.state.sharedWorker;
        } else {
          this.sharedWorker = new SharedWorker(SharedWorkerUrl);
          store.state.sharedWorker = this.sharedWorker;
        }
        this.sharedWorker.port.onmessage = (e) => {
          let data = e.data;
          if (data.type == "connected") {
            console.log("页面连接到SharedWorker...");
            this.uuid = data.uuid;
            this.sharedWorker.port.postMessage({
              type: "connected",
              data: localStorage.getItem("token"),
              url: baseUrlForWebSocket,
            });
          } else if (data.type == "msg") {
            let msg = JSON.parse(data.data);
            console.log(msg);
            if (!("data" in msg)) {
              if (msg.isBroadcast) {
                // 是广播消息
                store.state.notifyMessages.unshift(msg);
              } else {
                if (msg.type === 1) {
                  store.state.inviteMessages.unshift(msg);
                } else {
                  store.state.privateMessages.unshift(msg);
                }
              }
            }
          } else if (data.type == "log") {
            console.log(data.data);
          }
        };
      } else {
        console.log("浏览器不支持SharedWorker或WebSocket");
      }
    },
  },
  mounted() {
    this.createWebSocket();
    window.onbeforeunload = () => {
      if (this.sharedWorker) {
        this.sharedWorker.port.postMessage({
          type: "close",
          uuid: this.uuid,
        });
      }
    };
  },
  created() {
    // 获取用户未读信息数量
    request({
      url: "/api/message/message/count/unread",
      method: "get",
    }).then((resp) => {
      let data = resp.data;
      if (data.code === 0) {
        store.state.msgCount = data.data;
      }
    });
  },
};
</script>

<template>
  <div>
    <el-container>
      <!--      HEADER-->
      <el-header style="margin: 0; padding: 0">
        <el-affix>
          <el-menu background-color="#b88230" text-color="white" mode="horizontal" :ellipsis="false" router>
            <el-image src="/logo_white.png" style="
                width: auto;
                height: 60px;
                margin-left: 6%;
                cursor: pointer;
              " @click="this.$router.push('/')" />
            <el-menu-item index="/discover">
              <el-icon>
                <Opportunity />
              </el-icon>
              发现
            </el-menu-item>
            <el-menu-item index="/message">
              <el-icon>
                <el-badge is-dot :hidden="!hasMsg">
                  <BellFilled />
                </el-badge>
              </el-icon>
              消息
            </el-menu-item>
            <div class="flex-grow" />
            <!--            <el-menu-item index="/project">-->
            <!--              <el-icon>-->
            <!--                <FolderAdd/>-->
            <!--              </el-icon>-->
            <!--              新建知识库-->
            <!--            </el-menu-item>-->
            <el-menu-item index="/project">
              <el-icon>
                <Collection />
              </el-icon>
              知识库列表
            </el-menu-item>

            <el-sub-menu index="/user">
              <template #title>
                <div v-if="this.$store.state.isLogin" style="display: flex">
                  <!-- TODO  this.$store.state.user.avatarUrl可能为空-->
                  <el-avatar v-if="hasAvatar" @error="() => (hasAvatar = false)" :src="this.$store.state.user == null ||
                    this.$store.state.user.avatarUrl == null
                    ? ''
                    : this.$store.state.user.avatarUrl
                    " size="default" class="bordered-avatar" />
                  <el-avatar v-else :icon="UserFilled" size="default" class="bordered-avatar" />
                </div>
              </template>
              <el-menu-item index="/about">
                <el-icon>
                  <OfficeBuilding />
                </el-icon>
                关于我们
              </el-menu-item>
              <el-menu-item index="/user">
                <el-icon>
                  <UserFilled />
                </el-icon>
                个人信息
              </el-menu-item>
              <el-menu-item index="/logout">
                <el-icon>
                  <SwitchButton />
                </el-icon>
                退出登录
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-affix>
      </el-header>

      <!--      MAIN-->
      <el-main style="
          margin: 0;
          padding: 0;
          width: 100%;
          min-height: calc(100vh - 60px);
          overflow: auto;
        ">
        <!--        知识库设置的dialog-->
        <SettingProjectDialog />

        <!--        新建知识库的dialog-->
        <AddProjectDialog />

        <!--        阅读信息的dialog-->
        <ReadMessageDialog />

        <!--        添加Mock的Dialog-->
        <AddMockDialog />

        <router-view />
      </el-main>

      <!--      FOOTER-->
      <MyFooter :hidden="this.$route.params.projectId !== undefined" />
    </el-container>
  </div>
</template>

<style scoped>
.flex-grow {
  flex-grow: 1;
}

.bordered-avatar {
  border: 2px solid #898c8f;
  /* 设置描边颜色和宽度 */
}
</style>